package com.jiyun.purse.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiyun.pojo.purse.Purse;
import com.jiyun.purse.config.HttpUtils;
import com.jiyun.purse.config.ResultData;
import com.jiyun.purse.mapper.PurseMapper;
import com.jiyun.purse.service.PurseService;
import com.jiyun.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class PurseServiceImpl implements PurseService {
    @Autowired
    private PurseMapper purseMapper;

    /**
     * 根据用户ID查找钱包
     *
     * @param userId 用户ID
     * @return 返回钱包信息封装在Result对象中
     */
    @Override
    public Result findPurse(Integer userId) {
        return Result.ok(purseMapper.findPurse(userId));
    }

    /**
     * 根据钱包ID查找钱包
     *
     * @param id 钱包ID
     * @return 返回钱包信息封装在Result对象中
     */
    @Override
    public Result findPurseById(Integer id) {
        return Result.ok(purseMapper.findPurseById(id));
    }

    /**
     * 删除钱包
     *
     * @param id 钱包ID
     * @return 返回删除结果封装在Result对象中
     */
    @Override
    public Result deletePurse(Integer id) {
        return Result.ok(purseMapper.deletePurse(id));
    }

    /**
     * 添加银行卡
     *
     * @param purse 钱包对象，包含银行卡信息
     * @return 返回操作结果，如果银行卡已存在且已绑定，则返回错误信息；
     * 如果银行卡存在但未绑定，则绑定成功；如果银行卡不存在，则添加并绑定
     */
    @Override
    public Result addCard(Purse purse) {
        Purse card = purseMapper.selectCard(purse.getBankCardNumber());
        if (null != card) {
            if (card.getBindStatus() == 1) {
                return Result.error("该账号已绑定");
            } else {
                purseMapper.bindStatus(card.getId());
                return Result.ok("绑定成功");
            }
        } else {
            String host = "https://mtbank.market.alicloudapi.com";
            String path = "/data/verify_bankcard";
            String method = "POST";
//          自己账号的appcode
            String appcode = "622d686883504b1997c1b504c33fb4d5";
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appcode);
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            //需要给X-Ca-Nonce的值生成随机字符串，每次请求不能相同
            headers.put("X-Ca-Nonce", UUID.randomUUID().toString());
//          headers.put("X-Ca-Nonce","6214686362041837");
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("card_number", purse.getBankCardNumber());
//          bodys.put("ext", "ext");


            try {
                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//              System.out.println(response.toString());
//              log.info("response:{}", response.toString());
                //获取response的body
//              System.out.println(EntityUtils.toString(response.getEntity()));

                String jsonStr = EntityUtils.toString(response.getEntity());

//              System.out.println(jsonStr);
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    ResultData resultData = objectMapper.readValue(jsonStr, ResultData.class);
//                  System.out.println("Request ID: " + resultData.getRequest_id());
//                  System.out.println("Bank: " + resultData.getResult().getBank());
                    purse.setBankName(resultData.getResult().getBank());
                    purse.setBankIcon(resultData.getResult().getLogo());
                    purse.setBindStatus(1);
                    purse.setIsDelete(0);
                    purse.setPasswordFreeStatus(0);
                    purse.setPrecedenceStatus(0);
                    purseMapper.addCard(purse);
                    return Result.ok("绑定成功");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.error("添加失败");
    }

    /**
     * 更新钱包的免密状态和优先状态
     *
     * @param id 钱包ID
     * @return 返回更新结果封装在Result对象中
     */
    @Override
    public Result updatePP(Integer id) {
        return Result.ok(purseMapper.updatePP(id));
    }

    /**
     * 更新钱包的免密状态和优先状态
     *
     * @param id 钱包ID
     * @return 返回更新结果封装在Result对象中
     */
    @Override
    public Result updatePS(Integer id) {
        Purse purse = purseMapper.selectPS();
        if (null != purse) {
            purseMapper.updatePS2(purse.getId());
        }
        return Result.ok(purseMapper.updatePS1(id));
    }

    /**
     * 修改钱包的免密状态为1
     *
     * @param id 钱包ID
     * @return 返回修改结果封装在Result对象中
     */
    @Override
    public Result updatePF(Integer id) {
        return Result.ok(purseMapper.updatePF(id));
    }

    /**
     * 修改钱包的免密状态为0
     *
     * @param id 钱包ID
     * @return 返回修改结果封装在Result对象中
     */
    @Override
    public Result updatePF1(Integer id) {
        return Result.ok(purseMapper.updatePF1(id));
    }
}
